package com.dengcj.ecology.common;

import cn.hutool.http.HttpRequest;
import com.dengcj.ecology.hrm.HrmUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dengchunjie
 * @Description: E9单点登录
 * @date 2022/3/25 11:06
 */
public class SsoUtil {

    // ecology地址
    private static final String ECOLOGY_HOST = "http://127.0.0.1";

    // ecology/WEB-INF/prop/weaverloginclient.properties 中配置的appid，ssss为默认自带的本地调用配置
    private static final String SSO_APP_ID = "ssss";

    /**
     * 获取ecology单点登录Token
     * @param loginid
     * @return
     */
    public static String getEcologySsoToken(String loginid){
        Map<String, Object> params = new HashMap<>();
        params.put("appid", SSO_APP_ID);
        params.put("loginid", loginid);
        String result = HttpRequest.post(ECOLOGY_HOST+"/ssologin/getToken").form(params).execute().body();

        return result;
    }

    /**
     * 获取ecology单点登录Token
     * @param userId
     * @return
     */
    public static String getEcologySsoTokenByWorkCode(int userId) {
        String loginid = HrmUtil.getUserLoginId(userId);

        if("".equals(loginid)){
            return "";
        } else {
            return getEcologySsoToken(loginid);
        }
    }

    /**
     * 按照规则添加ssoToken到Url中，ssoToken必须添加
     * @param targetUrl
     * @param ssoToken
     * @return
     */
    public String buildUrl(String targetUrl, String ssoToken) {
        // 先判断有没有路由标识"#"
        int indexOfRoute = targetUrl.indexOf("#");

        // 如果有路由标识则添加到路由标识之前
        if(indexOfRoute > -1) {
            String jumpUrl = targetUrl.substring(0, indexOfRoute);
            String routeUrl = targetUrl.substring(indexOfRoute);

            int indexOfQueMark = jumpUrl.indexOf("?");
            // 判断跳转地址有没有问号
            if(indexOfQueMark > -1){
                // 有问号则添加ssoToken到问号之后
                targetUrl = jumpUrl.substring(0, indexOfQueMark+1) + "ssoToken=" + ssoToken + "&" + jumpUrl.substring(indexOfQueMark+1)+routeUrl;
            } else {
                targetUrl = jumpUrl+"?ssoToken="+ssoToken+routeUrl;
            }
        } else {
            int indexOfQueMark = targetUrl.indexOf("?");
            // 判断有没有问号
            if(indexOfQueMark > -1){
                // 有问号则添加ssoToken到问号之后
                targetUrl = targetUrl.substring(0, indexOfQueMark+1) + "ssoToken=" + ssoToken + "&" + targetUrl.substring(indexOfQueMark+1);
            } else {
                targetUrl += "?ssoToken=" + ssoToken;
            }
        }

        return targetUrl;
    }
}
